package tiled.mapeditor.util;

import java.awt.Component;
import java.awt.HeadlessException;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import tiled.mapeditor.Resources;

public final class ConfirmingFileChooser extends JFileChooser
{
    private static final String UNKNOWN_TYPE_MESSAGE = Resources.getString("dialog.saveas.unknown-type.message");
    private static final String CONFIRM_MISMATCH = Resources.getString("dialog.saveas.confirm.mismatch");
    private static final String CONFIRM_MISMATCH_TITLE = Resources.getString("dialog.saveas.confirm.mismatch.title");
    private static final String FILE_EXISTS_MESSAGE = Resources.getString("general.file.exists.message");
    private static final String FILE_EXISTS_TITLE = Resources.getString("general.file.exists.title");

    public ConfirmingFileChooser(String currentDirectoryPath)
    {
        super(currentDirectoryPath);
    }

    public int showSaveDialog(Component component) throws HeadlessException
    {
        setDialogTitle(Resources.getString("dialog.saveas.title"));
        return super.showSaveDialog(component);
    }

    public ConfirmingFileChooser()
    {
        this(null);
    }

    public void approveSelection()
    {
        if (getDialogType() == OPEN_DIALOG)
        {
            super.approveSelection();
            return;
        }

        File file = new File(getSelectedFile().getAbsoluteFile());

        String filename = file.getName();
        int lastDot = filename.lastIndexOf('.');

        if ((lastDot == -1 || lastDot == filename.length() - 1) &&
                getFileFilter() instanceof ConfirmableFileFilter)
        {
            ConfirmableFileFilter filter =
                    (ConfirmableFileFilter)getFileFilter();
            String extension = filter.getDefaultExtension();

            if (extension == null)
            {
                JOptionPane.showMessageDialog(this, UNKNOWN_TYPE_MESSAGE);
                return;
            }

            setSelectedFile(file);
        }

        if (!getFileFilter().accept(file))
        {
            int result = JOptionPane.showConfirmDialog(
                    this,
                    CONFIRM_MISMATCH, CONFIRM_MISMATCH_TITLE,
                    JOptionPane.YES_NO_OPTION);

            if (result != JOptionPane.OK_OPTION)
            {
                return;
            }
        }

        if (file.exists())
        {
            int answer = JOptionPane.showConfirmDialog(
                    this,
                    FILE_EXISTS_MESSAGE, FILE_EXISTS_TITLE,
                    JOptionPane.YES_NO_OPTION);

            if (answer == JOptionPane.YES_OPTION)
            {
                super.approveSelection();
            }
        }
        else
        {
            super.approveSelection();
        }
    }
}
